package distributed.controller;

import org.w3c.dom.Node;

import distributed.entity.Event;
import distributed.entity.EventModel;
import distributed.entity.User;

import server.ClientState;
import server.Server;
import xml.Message;

/**
 * Controller to handle the implementation of chat
 * @author Sam Jaffe
 *
 */
public class ChatController implements IProtocolController{

	/** Processes a message from a client */
	public Message process(ClientState state, Message request) {
		String xmlString;
		//Get the chatRequest node
		Node base = request.contents.getFirstChild();
		
		//Get the id & username
		String id = base.getAttributes().getNamedItem("id").getNodeValue();
		String user = base.getAttributes().getNamedItem("user").getNodeValue();
		String text;
		try { //Try and grab the text (will crash if the text node has no children)
		text = base.getFirstChild().getFirstChild().getNodeValue();
		} catch (NullPointerException npe) {
			return new Message(Message.responseHeader(request.id(), "Please enter some text") +
					"<chatResponse id='" + id + "' user='" + user + "'><text/></chatResponse>" +
							"</response>");
		}
		
		// Else we'll make our reply
		xmlString = Message.responseHeader(request.id()) + "<chatResponse id='" + id + "' user='"
				+ user + "'><text>" + text + "</text></chatResponse></response>";
		
		Message send = new Message(xmlString);
		// And send it to everyone in the event
		Event event = EventModel.getInstance().getEvent(id);
		for (User u : event.getUsers())
			if (u != null && !u.getID().equals(state.id()))
				if (Server.getState(u.getID()) != null)
					Server.getState(u.getID()).sendMessage(send);
		
		return send;
	}

	/**
	 * @ChatController
	 */
	public IProtocolController newCopy() {
		return new ChatController();
	}

}
